<template>
  <div class="system-dept-dialog-container">
    <el-dialog :title="dataForm.seatId ? $t('common.editBtn') : $t('common.addBtn')" v-model="visible" width="600">
      <el-form ref="seatDialogFormRef" :model="dataForm" label-width="90px" :rules="dataRules" v-loading="loading">
        <el-form-item label="座位号" prop="seatName">
          <el-input v-model="dataForm.seatName" placeholder="请输入座位号" clearable/>
        </el-form-item>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
					<el-button type="primary" @click="onSubmit" :disabled="loading">{{
              $t('common.confirmButtonText')
            }}</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="infusionSeatDialog">
import {useI18n} from 'vue-i18n';
import {getSeatObj, addSeatObj, putSeatObj} from '/@/api/infusion/config';
import {useMessage} from '/@/hooks/message';
import {rule} from '/@/utils/validate';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const {t} = useI18n();
// 定义变量内容
const seatDialogFormRef = ref();
const dataForm = reactive({
  seatId: '',
  seatName: ''
});
const visible = ref(false);
const loading = ref(false);

const dataRules = ref({
  seatName: [{validator: rule.overLength, trigger: 'blur'},{required: true, message: '座位号不能为空', trigger: 'blur'}],
});

// 打开弹窗
const openDialog = (type: string, id: string) => {
  visible.value = true;
  dataForm.seatId = '';

  seatDialogFormRef.value?.resetFields();

  if (type === 'edit') {
    getSeatObj(id)
        .then((res) => {
          Object.assign(dataForm, res.data);
        })
        .catch((err) => {
          useMessage().error(err.msg);
        });
  }
};

// 提交
const onSubmit = async () => {
  const valid = await seatDialogFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  try {
    loading.value = true;
    dataForm.seatId ? await putSeatObj(dataForm) : await addSeatObj(dataForm);
    useMessage().success(t(dataForm.seatId ? 'common.editSuccessText' : 'common.addSuccessText'));
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>
